﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SQLite;

public partial class BasicInfo_AddUser : UDCPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DepartDataBind();
            RoleDataBind();
        }
    }

    private void DepartDataBind()
    {
        string sqlstr = "select did,dname from ud_depart_t";
        DepartList.DataSource = SQLiteHelper.ExecuteDataset(sqlstr, null);
        DepartList.DataTextField = "dname";
        DepartList.DataValueField = "did";
        DepartList.DataBind();
        DepartList.SelectedIndex = 0;
    }

    private void RoleDataBind()
    {
        string sqlstr = "select rid,rolename from ud_role_t";
        RoleList.DataSource = SQLiteHelper.ExecuteDataset(sqlstr, null);
        RoleList.DataTextField = "rolename";
        RoleList.DataValueField = "rid";
        RoleList.DataBind();
        RoleList.SelectedIndex = 0;
    }

    protected void addUser_Click(object sender, EventArgs e)
    {
        string sqlstr = "insert into ud_user_t values(null,:username,:loginname,:password,:did,1);"
             + "select last_insert_rowid();";
        SQLiteParameter[] spc = {
        new SQLiteParameter(":username", DbType.String, 20),
        new SQLiteParameter(":loginname", DbType.String,20),
        new SQLiteParameter(":password", DbType.String,20),
        new SQLiteParameter(":did", DbType.Int32)
        };
        spc[0].Value = username.Value.Trim();
        spc[1].Value = loginname.Value.Trim();
        spc[2].Value = password.Text.Trim();
        spc[3].Value = Int32.Parse(DepartList.SelectedValue);
        UserRoleBind(Int32.Parse(SQLiteHelper.ExecuteScalar(sqlstr, spc).ToString()));        
    }

    private void UserRoleBind(int uid)
    {
        string sqlstr = "insert into ud_user_role_t values(:uid,:rid)";
        SQLiteParameter[] spc = {
        new SQLiteParameter(":uid", DbType.Int32),
        new SQLiteParameter(":rid", DbType.Int32)
        };
        spc[0].Value = uid;
        spc[1].Value = Int32.Parse(RoleList.SelectedValue);
        int res = SQLiteHelper.ExecuteNonQuery(sqlstr, spc);
        if (res > 0)
        {
            Response.Redirect("UserManage.aspx");
        }
        else
        {
            msg.Text = "用户新增失败！";
        }
    }
}